<template>
  <div class="app-container">
    <div class="wise-crud">
      <div class="table-show">
        <div class="operation-block">
          <el-row class="oper-btn" :gutter="10">
            <el-col :span="16">
              <el-button type="primary" @click="handleAdd()"><i class="el-icon-plus" />添加</el-button>
            </el-col>
            <el-col :span="8" class="text-right">
              <el-input v-model="search.key" placeholder="请输入内容" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
              </el-input>
            </el-col>
          </el-row>
        </div>
        <!--table-->
        <el-table :data="tableData" border highlight-current-row row-key="id" lazy :load="load"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <template v-for="(column, index) in columns">
            <el-table-column v-if="column.type=='selection'" :key="index" type="index" width="50" />
            <el-table-column v-else-if="column.type=='index'" :key="index" type="index" width="50" />
            <el-table-column v-else-if="column.type=='slot'" :key="index" :index="index" :column-key="column.columnKey"
              :label="column.label" :width="column.width" :min-width="column.minWidth" :fixed="column.fixed"
              :render-header="column.renderHeader" :sortable="column.sortable" :header-align="column.align">
              <template slot-scope="scope">
                <slot :name="column.prop" :row="scope.row" />
              </template>
            </el-table-column>
            <el-table-column v-else-if="column.type=='date'" :key="index" :index="index" :column-key="column.columnKey"
              :label="column.label" :width="column.width" :min-width="column.minWidth" :fixed="column.fixed"
              :render-header="column.renderHeader" :sortable="column.sortable" :header-align="column.align">
              <template slot-scope="scope">
                {{ scope.row[column.prop]|dateFormat(column.format) }}
              </template>
            </el-table-column>
            <el-table-column v-else-if="column.type=='radio'" :key="index" :index="index" :column-key="column.columnKey"
              :label="column.label" :width="column.width" :min-width="column.minWidth" :fixed="column.fixed"
              :render-header="column.renderHeader" :sortable="column.sortable" :header-align="column.align">
              <template slot-scope="scope">
                <template v-if="column.dataDic">
                  {{ setDictData(column.dataDic,scope.row[column.prop]) }}
                </template>
                <template v-else>
                  {{ scope.row[column.prop] }}
                </template>
              </template>
            </el-table-column>
            <el-table-column v-else-if="column.type=='render'" :key="index" :index="index"
              :column-key="column.columnKey" :label="column.label" :width="column.width" :min-width="column.minWidth"
              :fixed="column.fixed" :render-header="column.renderHeader" :sortable="column.sortable"
              :header-align="column.align">
              <template slot-scope="scope">
                <column-render :row="scope.row" :index="scope.$index" :render="column.render" />
              </template>
            </el-table-column>
            <el-table-column v-else-if="column.type=='switch'" :key="index" :index="index"
              :column-key="column.columnKey" :label="column.label" :width="column.width" :min-width="column.minWidth"
              :fixed="column.fixed" :render-header="column.renderHeader" :sortable="column.sortable"
              :header-align="column.align">
              <template slot-scope="scope">
                <el-switch v-model="scope.row[column.prop]" :active-text="column.active"
                  :inactive-text="column.inactive" :active-value="column.activeValue"
                  :inactive-value="column.inactiveValue"
                  @change="switchHandle($event,scope.row,column.url,column.params)" />
              </template>
            </el-table-column>
            <el-table-column v-else-if="column.type=='handle'" :key="index" :index="index"
              :column-key="column.columnKey" :label="column.label" :width="column.width" :min-width="column.minWidth"
              :fixed="column.fixed" :render-header="column.renderHeader" :sortable="column.sortable"
              :header-align="column.align">
              <template slot-scope="scope">
                <el-button v-if="column.handle.indexOf('edit')!=-1" type="primary" size="small" round
                  @click.native.prevent="handleEdit(scope.row)">编辑
                </el-button>
                <el-button v-if="column.handle.indexOf('view')!=-1" type="info" size="small" round
                  @click.native.prevent="handleView(scope.row)">查看
                </el-button>
                <el-button v-if="column.handle.indexOf('delete')!=-1" type="danger" size="small" round
                  @click.native.prevent="handleDelete(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
            <el-table-column v-else :key="index" :prop="column.prop" :index="index" :column-key="column.columnKey"
              :label="column.label" :width="column.width" :min-width="column.minWidth" :fixed="column.fixed"
              :render-header="column.renderHeader" :sortable="column.sortable" :header-align="column.align" />
          </template>
        </el-table>
        <div class="page-block">
          <pagination :background="true" layout="total,prev, pager, next" :total="ts" :page.sync="page.p"
            :limit.sync="page.ps" @pagination="getTableData" />
        </div>
      </div>
      <el-dialog ref="drawer" :title="title" :visible.sync="drawer" append-to-body destroy-on-close>
        <div v-if="drawer" class="draw-body">
          <wise-form :columns="formItems" :loading="loading" :old-object="object" @on-submit="submitHandle" />
        </div>
      </el-dialog>
      <el-dialog ref="viewDrawer" title="查看" :visible.sync="viewDrawer" append-to-body close-on-press-escape
        destroy-on-close>
        <div class="draw-body">
          <wise-view :columns="viewItems" :object="object" />
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import WiseForm from '@/components/Crud/Form/wiseForm'
  import WiseView from '@/components/Crud/View/wiseView'
  import Pagination from '../../../../components/Pagination/index'
  import {
    postHandle
  } from '../../../../api'
  export default {
    name: 'DataDictionary',
    components: {
      Pagination,
      WiseView,
      WiseForm
    },
    data() {
      return {
        urls: {
          list: '/api/v1/welder-sbtx-second/dictionary',
          add: '/api/v1/welder-sbtx-second/dictionary-comb/create',
          show: '/api/v1/welder-sbtx-second/dictionary/show/',
          update: '/api/v1/welder-sbtx-second/dictionary-comb/update/',
          delete: '/api/v1/welder-sbtx-second/dictionary-comb/remove/'
        },
        fields: [{
            label: '序号',
            type: 'index',
            use: ['table']
          },
          {
            label: '字典名称',
            prop: 'name',
            type: 'text',
            maxlength: 20,
            labelWidth: '120px',
            rules: [{
              required: true,
              message: '请输入字典名称',
              trigger: 'blur'
            }],
            placeholder: '请输入名称',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '字典编码',
            prop: 'code',
            type: 'text',
            maxlength: 20,
            labelWidth: '120px',
            rules: [{
              required: true,
              message: '请输入字典编码',
              trigger: 'blur'
            }],
            placeholder: '请输入字典编码',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '上级字典',
            prop: 'parent',
            type: 'select',
            labelWidth: '120px',
            url: '/api/v1/welder-sbtx-second/dictionary',
            labelKey: 'name',
            valueKey: 'id',
            objKeys: [{
                field: 'pdId',
                key: 'id'
              },
              {
                field: 'pdCode',
                key: 'code'
              }
            ],
            placeholder: '请选择上级字典',
            use: ['add']
          },
          {
            label: '字典内容',
            prop: 'content',
            type: 'text',
            maxlength: 100,
            labelWidth: '120px',
            rules: [{
              required: true,
              message: '请输入字典内容',
              trigger: 'change'
            }],
            placeholder: '请输入字典内容',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '描述',
            prop: 'remark',
            type: 'textarea',
            maxlength: 500,
            labelWidth: '120px',
            placeholder: '请输入描述',
            use: ['add', 'view', 'edit', 'search']
          },
          {
            label: '操作',
            type: 'handle',
            use: ['table'],
            handle: ['edit', 'view', 'delete']
          }
        ],
        columns: [],
        search: {
          key: '',
          fields: []
        },
        loading: false,
        formItems: [],
        submitLoading: false,
        object: {},
        drawer: false,
        title: '',
        viewDrawer: false,
        viewItems: [],
        tableData: [],
        ts: 0,
        page: {
          p: 1,
          ps: 20
        }
      }
    },
    mounted() {
      this.init()
      this.getTableData()
    },
    methods: {
      init() {
        this.columns = []
        this.search.fields = []
        if (this.fields && this.fields.length > 0) {
          this.fields.forEach(item => {
            if (item.use.indexOf('table') !== -1) {
              this.columns.push({
                label: item.label,
                type: item.tableType ? item.tableType : item.type,
                prop: item.prop,
                dataDic: item.dataDic,
                handle: item.handle
              })
            }
            if (item.use.indexOf('search') !== -1) {
              this.search.fields.push(item.prop)
            }
          })
        }
      },
      setFromItem(hanlde) {
        this.formItems = []
        if (this.fields && this.fields.length > 0) {
          this.fields.forEach(item => {
            if (item.use.indexOf(hanlde) !== -1) {
              this.formItems.push({
                label: item.label,
                type: item.type,
                prop: item.prop,
                dataDic: item.dataDic,
                labelWidth: item.labelWidth,
                rules: item.rules,
                url: item.url,
                labelKey: item.labelKey,
                valueKey: item.valueKey,
                objKeys: item.objKeys,
                maxlength: item.maxlength,
                placeholder: item.placeholder
              })
            }
          })
        }
      },
      setViewItem() {
        this.viewItems = []
        if (this.fields && this.fields.length > 0) {
          this.fields.forEach(item => {
            if (item.use.indexOf('view') !== -1) {
              this.viewItems.push({
                label: item.label,
                type: item.type,
                prop: item.prop,
                labelWidth: item.labelWidth,
                dataDic: item.dataDic
              })
            }
          })
        }
      },
      getObjectById(id) {
        postHandle(this.urls.show + id, {}).then(response => {
          this.object = response.result
        })
      },
      deleteObjectById(id) {
        postHandle(this.urls.delete + id, {}).then(response => {
          this.page.p = 1
          this.getTableData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(error => {
          console.error(error)
          // this.$message.error('操作失败')
        })
      },
      handleAdd() {
        this.setFromItem('add')
        this.title = '新增'
        this.drawer = true
      },
      handleEdit(row) {
        this.setFromItem('edit')
        this.title = '编辑'
        this.getObjectById(row.id)
        this.drawer = true
      },
      handleView(row) {
        this.setViewItem()
        this.getObjectById(row.id)
        this.viewDrawer = true
      },
      handleDelete(row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteObjectById(row.id)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      submitHandle(obj) {
        this.loading = true
        let url = this.urls.add
        if (obj.id) {
          url = this.urls.update + obj.id
        }
        postHandle(url, {
          obj
        }).then(response => {
          this.$message('操作成功')
          this.loading = false
          this.drawer = false
          this.page.p = 1
          this.getTableData()
        }).catch(error => {
          console.error(error)
          this.loading = false
          // this.$message.error('操作失败')
        })
      },
      handleSearch() {
        this.page.p = 1
        this.getTableData()
      },
      getTableData() {
        const req = {
          d: {
            filters: [{
              field: 'pdId',
              operator: 'ISNULL'
            }],
            page: this.page,
            search: this.search,
            retPage: true
          }
        }
        postHandle(this.urls.list, req).then(response => {
          const data = response.result
          data.forEach(item => {
            item['hasChildren'] = true
          })
          this.tableData = data
          this.ts = response.page.ts
        })
      },
      load(tree, treeNode, resolve) {
        console.log(tree, treeNode)
        const req = {
          d: {
            filters: [{
              field: 'pdId',
              operator: 'EQUALS',
              value: tree.id
            }],
            page: {
              p: 1,
              ps: 9999
            },
            search: this.search
          }
        }
        postHandle(this.urls.list, req).then(response => {
          const data = response.result
          data.forEach(item => {
            item['hasChildren'] = true
          })
          resolve(data)
        })
      }
    }
  }
</script>

<style>

</style>